package com.lagou.dao;

import com.lagou.entity.Account;
import com.lagou.utils.DateUtils;
import com.lagou.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class AccountDao {
    /**
     * a) 使用连接池创建QueryRunner对象；
     * b) 判断转出方是否有足够余额，如果不足，提示信息：”余额不足！”，并结束程序；
     * c) 通过卡号 进行转账的操作；
     * d) 转账结束后, 将转入、转出记录分别写入到Transaction表中。
     */
    QueryRunner qr = new QueryRunner(DruidUtils.GetDataSource());
    public int updateAccount(String card1,String card2) throws SQLException {
        // todo 判断要转的卡里的钱是否大于5000
        String sql = "select * from account where card = ?";
        String sql3 = "select * from account where card = ?";
        Account money2 = qr.query(sql3, new BeanHandler<Account>(Account.class), card2);
        // 转钱的账户
        Account money = qr.query(sql, new BeanHandler<Account>(Account.class), card1);
        if(money.getBalance()<5000){
            System.out.println("余额不足");
            return 0;
        }else{
            String sql1 = "update account set balance = balance-5000 where card = ? ";
            qr.update(sql1,card1);
            String sql2 = "update account set balance = balance+5000 where card = ? ";
            qr.update(sql2,card2);
            insertTransaction(money,money2);
        }
        System.out.println("转账结束");
        return 1;
    }
    /**
     * 把转账记录插入到另外一个表中
     *
     */
    public void insertTransaction(Account a,Account b) throws SQLException {
        String zhuanChu = "insert into transaction values(?,?,?,?,?)";
        String time = DateUtils.getDateFormart();
        Object[] o ={null,a.getCard(),"转出",5000,time};
        qr.update(zhuanChu,o);

        String zhuanRu = "insert into transaction values(?,?,?,?,?)";
        Object[] o1 ={null,b.getCard(),"转入",5000,time};
        qr.update(zhuanRu,o1);
    }
}
